package pub.digur.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class Parser
{
	public static Status getStatus(XMLStreamReader parser, Status status) throws XMLStreamException
	{
		while (parser.hasNext())
		{
			int event = parser.next();
			if (event == XMLStreamConstants.START_ELEMENT)
			{
				if (parser.getLocalName().equals("profile_image_url"))
				{
					parser.next();
					if (parser.isCharacters())
					{
						status.profileImage = parser.getText();
						status.profileImage = status.profileImage.replace("24x24", "48x48");
					}
				}
				else if (parser.getLocalName().equals("screen_name"))
				{
					parser.next();
					if (parser.isCharacters())
					{
						status.screenName = parser.getText();
					}
				}
				else if (parser.getLocalName().equals("text"))
				{
					parser.next();
					if (parser.isCharacters())
					{
						status.text = parser.getText();
					}
				}
				else if (parser.getLocalName().equals("created_at"))
				{
					parser.next();
					if (parser.isCharacters())
					{
						status.createdDate = parser.getText();
					}
				}
			}
			else if (event == XMLStreamConstants.END_ELEMENT && parser.getLocalName().equals("status"))
			{
				break;
			}
		}
		
		return status;
	}
	
	public static XMLStreamReader getParser(HttpSession session, HttpServletResponse response) throws Exception
	{
		response.setCharacterEncoding("UTF-8");

		String name = (String) session.getAttribute("name");
		String password = (String) session.getAttribute("password");
		String urlStr = "http://api.minicloud.com.cn/statuses/user_timeline.xml?name=" + name;

		System.out.println(urlStr);

		URL url = new URL(urlStr);
		URLConnection conn = url.openConnection();

		conn.setRequestProperty("Authorization", "Basic " + Encoder.base64Encode(name + ":" + password));

		InputStream in = null;
		try
		{
			in = conn.getInputStream();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		XMLInputFactory factory = XMLInputFactory.newInstance();
		XMLStreamReader parser = factory.createXMLStreamReader(in);
		
		return parser;
	}
}
